#include "stdafx.h"
#include "Window.h"

const wchar_t* WindowClass = L"Engine Window";
namespace os
{		
	LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
	{
		switch (message)
		{
		case WM_DESTROY:
			PostQuitMessage(0);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		return 0;
	}
	void registerWindowClass()
	{		
		WNDCLASSEX wcex;	
				
	
		wcex.cbSize        = sizeof(WNDCLASSEX);
		wcex.style         = 0;
		wcex.lpfnWndProc   = WndProc;
		wcex.cbClsExtra    = 0;
		wcex.cbWndExtra    = 0;
		wcex.hInstance     = GetModuleHandle(nullptr);
		wcex.hIcon         = NULL;
		wcex.hCursor       = NULL;
		wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
		wcex.lpszMenuName  = NULL;
		wcex.lpszClassName = WindowClass;
		wcex.hIconSm       = NULL;


		assert(RegisterClassEx(&wcex));
	}
	Window::Window() : handle_(nullptr)
	{		
		static bool registered = false;
		if(!registered)
		{
			registerWindowClass();
		}
		handle_ = CreateWindow(WindowClass, L"Engine Window", WS_OVERLAPPEDWINDOW,
			CW_USEDEFAULT, 0, 1920, 1080, NULL, NULL, nullptr, NULL);
		assert(handle_);
	}
	Window::~Window()
	{
		DestroyWindow(handle_); 
		handle_ = nullptr;
	}
	void Window::show()
	{		
		ShowWindow(handle_, SW_SHOW);
	}
	bool Window::update()
	{
		MSG msg;
		if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if(msg.message == WM_QUIT)
			{
				return false;
			}
		}
		return true;
	}


	math::Sizei Window::clientSize() const
	{
		RECT rect;
		GetClientRect(handle_, &rect);
		return math::Sizei(rect.right - rect.left, rect.bottom - rect.top);
	}
	NativeHandle Window::nativeHandle() const
	{
		return handle_;
	}
}